<?php
session_start();
// Session::instance();

class AuthFilter {
    private static $UNAUTHORIZED_URL = '/page/unauthorized';

    public static function checkAuthorization() {
        $sessionData = SessionData::instance();
        $user = $sessionData->getAuthUser();
        $org = $sessionData->getAuthOrg();
        if (strpos($_SERVER['PHP_SELF'], '/admin/')) {
            if (! $user || ! $user['is_admin']) {
                url::redirect(self::$UNAUTHORIZED_URL);
            }
        }
        else if (strpos($_SERVER['PHP_SELF'], '/user/')) {
            if ($user == NULL) {
                url::redirect(self::$UNAUTHORIZED_URL);
            }
        }
        else if (strpos($_SERVER['PHP_SELF'], '/org/')) {
            if ($org == NULL) {
                url::redirect(self::$UNAUTHORIZED_URL);
            }
        }
        else if (strpos($_SERVER['PHP_SELF'], '/reception/')) {
        	if ($user == NULL) {
        		url::redirect(self::$UNAUTHORIZED_URL);
        	}
        	if (! $user['receptionSeminar']) {
        		url::redirect('/user/userSpace/welcome');
        	}
        }
    }

    /**
     * Every POST request must contain a _formId parameter with value that is registered
     * in SessionData. If it does not, end the request.
     */
    public static function checkFormId() {
        $sessionData = SessionData::instance();
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $formId = $_POST[auth::$FORM_ID];
            if (! $formId) {
                die('No form ID');
            }
            if (! $sessionData->checkAndRemoveFormId($formId)) {
                die('Invalid form ID');
            }
        }
    }
}
Event::add('system.ready', array('AuthFilter', 'checkAuthorization'));
// Event::add('system.ready', array('AuthFilter', 'checkFormId'));
